package cn.edu.ctbu.dp01.aop;

import cn.edu.ctbu.dp01.constant.REnum;
import cn.edu.ctbu.dp01.exception.RException;
import cn.edu.ctbu.dp01.util.RUtil;
import cn.edu.ctbu.dp01.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionHandle {
    private static final Logger log = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e) {
        log.error("Exception occurred", e);

        if (e instanceof RException) {
            RException rException = (RException) e;
            log.error("RException caught: code={}, message={}", rException.getCode(), rException.getMessage());
            return RUtil.error(rException.getCode(), rException.getMessage());
        } else {
            log.error("Other exception caught: {}", e.getMessage());
            return RUtil.error(REnum.UNKOWN_ERR);
        }
    }
}